import React, { Component } from 'react'
import { StyleSheet, View } from 'react-native'
import { Modal } from 'antd-mobile'
import { inject, observer } from 'mobx-react/native'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'

import { Contacts, IconButton } from '../components'
import store from '../store'

@inject('actions', 'store')
@observer
@graphql(
  gql`
    mutation($selfId: ID!, $targetId: ID!) {
      addToContacts(contacts1UserId: $selfId, contacts2UserId: $targetId) {
        contacts2User {
          id
        }
      }
    }
  `,
  { name: 'addContact' },
)
@graphql(
  gql`
    query {
      user {
        id
        contacts {
          id
          role
          name
        }
      }
    }
  `,
  {
    options: ({ store }) => ({
      variables: { userId: store.user.id },
      fetchPolicy: 'network-only',
    }),
  },
)
export class ContactsScreen extends Component {
  static navigationOptions = ({
    navigation,
    // screenProps: { addContact, store },
  }) => ({
    headerRight: (
      <IconButton
        name="person-add"
        onPress={() =>
          Modal.prompt(
            'Add Contact',
            undefined,
            [
              { text: 'Cancel' },
              {
                text: 'Submit',
                onPress: async value => {
                  const addContact = navigation.getParam('addContact')
                  const refetch = navigation.getParam('refetch')
                  if (addContact && refetch) {
                    await addContact({
                      variables: {
                        selfId: store.user.id,
                        targetId: value,
                      },
                    })
                    refetch()
                  }
                },
              },
            ],
            undefined,
            undefined,
            ['Contact ID'],
          )
        }
      />
    ),
  })

  componentWillReceiveProps({ addContact, data: { refetch }, navigation }) {
    if (!navigation.getParam('addContact')) navigation.setParams({ addContact })
    if (!navigation.getParam('refetch')) navigation.setParams({ refetch })
  }

  render = () => (
    <View style={styles.container}>
      <Contacts
        contacts={this.props.data.loading ? [] : this.props.data.user.contacts}
        loading={this.props.data.loading}
        onRefresh={this.props.data.refetch}
      />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
})
